package cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation;

import cn.gcyl.module.biz.dal.dataobject.SysMemberUserDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.meetingplan.MeetingPlanDO;
import cn.gcyl.module.biz.dal.dataobject.specialmeeting.SpecialMeetingDO;
import cn.gcyl.module.biz.dal.mysql.SysMemberUserMapper;
import cn.gcyl.module.biz.dal.mysql.conferenceregistrationinformation.ConferenceRegistrationInformationMapper;
import cn.gcyl.module.biz.dal.mysql.meetingplan.MeetingPlanMapper;
import cn.gcyl.module.biz.dal.mysql.specialmeeting.SpecialMeetingMapper;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.gcyl.framework.common.pojo.PageParam;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.framework.common.pojo.CommonResult;
import cn.gcyl.framework.common.util.object.BeanUtils;
import static cn.gcyl.framework.common.pojo.CommonResult.success;

import cn.gcyl.framework.excel.core.util.ExcelUtils;

import cn.gcyl.framework.apilog.core.annotation.ApiAccessLog;
import static cn.gcyl.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.*;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceRegistrationInformationDO;
import cn.gcyl.module.biz.service.conferenceregistrationinformation.ConferenceRegistrationInformationService;

@Tag(name = "管理后台 - 会议报名信息")
@RestController
@RequestMapping("/biz/conference-registration-information")
@Validated
public class ConferenceRegistrationInformationController {

    @Resource
    private ConferenceRegistrationInformationService conferenceRegistrationInformationService;

    @Resource
    private ConferenceRegistrationInformationMapper conferenceRegistrationInformationMapper;

    @Resource
    private SpecialMeetingMapper specialMeetingMapper;
    @Resource
    private MeetingPlanMapper meetingPlanMapper;

    @Resource
    private SysMemberUserMapper sysMemberUserMapper;

    @PutMapping("/review-meeting")
    @Operation(summary = "审核会议报名信息")
//    @PreAuthorize("@ss.hasPermission('member:user:update-remake')")
    public CommonResult<Boolean> reviewMeeting(@Valid @RequestBody reviewMeetingInformationReqVO updateReqVO) {
        ConferenceRegistrationInformationDO conferenceRegistrationInformationDO = conferenceRegistrationInformationMapper.selectById(updateReqVO.getId());
        if (ObjectUtil.isNotEmpty(conferenceRegistrationInformationDO)) {
            conferenceRegistrationInformationDO.setIsFree(updateReqVO.getIsFree());
            conferenceRegistrationInformationDO.setPayStatus(1);
            if (ObjectUtil.isNotEmpty(updateReqVO.getRejectionReason())) {
                conferenceRegistrationInformationDO.setRejectionReason(updateReqVO.getRejectionReason());
            }
            conferenceRegistrationInformationDO.setExamineTime(LocalDateTime.now());
            int i = conferenceRegistrationInformationMapper.updateById(conferenceRegistrationInformationDO);
            if (i ==0){
                return success(false);
            }
        }
        return success(true);
    }
    @PostMapping("/create")
    @Operation(summary = "创建会议报名信息")
//    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:create')")
    public CommonResult<Long> createConferenceRegistrationInformation(@Valid @RequestBody ConferenceRegistrationInformationSaveReqVO createReqVO) {
        return success(conferenceRegistrationInformationService.createConferenceRegistrationInformation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新会议报名信息")
//    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:update')")
    public CommonResult<Boolean> updateConferenceRegistrationInformation(@Valid @RequestBody ConferenceRegistrationInformationSaveReqVO updateReqVO) {
        conferenceRegistrationInformationService.updateConferenceRegistrationInformation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除会议报名信息")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:delete')")
    public CommonResult<Boolean> deleteConferenceRegistrationInformation(@RequestParam("id") Long id) {
        conferenceRegistrationInformationService.deleteConferenceRegistrationInformation(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除会议报名信息")
//                @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:delete')")
    public CommonResult<Boolean> deleteConferenceRegistrationInformationList(@RequestParam("ids") List<Long> ids) {
        conferenceRegistrationInformationService.deleteConferenceRegistrationInformationListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得会议报名信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:query')")
    public CommonResult<ConferenceUserRegistrationInformationPO> getConferenceRegistrationInformation(@RequestParam("id") Long id) {
        ConferenceUserRegistrationInformationPO meetingInfo = conferenceRegistrationInformationService.getMeetingInfo(id);
        return success(meetingInfo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户会议报名信息分页")
//    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<ConferenceUserRegistrationInformationPO>>
    getMeetingListPage(@Valid ConferenceMeetingInformationPageReqVO pageVO) {
        PageResult<ConferenceUserRegistrationInformationPO> pageResult =
                conferenceRegistrationInformationService.getMeetingListPage(pageVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出会议报名信息 Excel")
//    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportConferenceRegistrationInformationExcel(@Valid ConferenceMeetingInformationPageReqVO pageReqVO,
                                                             HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ConferenceUserRegistrationInformationPO> list = conferenceRegistrationInformationService
                .getMeetingListPage(pageReqVO).getList();
        for (ConferenceUserRegistrationInformationPO po : list) {
            // 添加非空校验
            if (po.getMeetingId() != null) {
                SpecialMeetingDO specialMeetingDO = specialMeetingMapper.selectById(po.getMeetingId());
                if (specialMeetingDO != null) {
                    po.setMeetingName(specialMeetingDO.getMeetingName());
                    po.setMeetingSynopsis(specialMeetingDO.getMeetingSynopsis());
                    po.setMeetingAddress(specialMeetingDO.getMeetingAddress());
                    po.setMeetingTime(specialMeetingDO.getStartTime()+"-"+specialMeetingDO.getEndTime());
                    po.setIsFreeMeeting(specialMeetingDO.getIsFreeMeeting());
                }
            }
            if (po.getUserId() != null) {
                SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(po.getUserId());
                if (sysMemberUserDO != null) {
                    po.setNickname(sysMemberUserDO.getNickname());
                    po.setMobile(sysMemberUserDO.getMobile());
                }
            }
            // 处理会议方案数据
            if (po.getMeetingPlanId() != null && !po.getMeetingPlanId().isEmpty()) {
                try {
                    // 将逗号分隔的字符串转换为Long列表
                    List<Long> meetingPlanIds = Arrays.stream(po.getMeetingPlanId().split(","))
                            .map(String::trim)
                            .map(Long::valueOf)
                            .collect(Collectors.toList());

                    // 查询对应的会议方案数据
                    List<MeetingPlanDO> meetingPlanDOS = meetingPlanMapper.selectList(
                            new LambdaQueryWrapper<MeetingPlanDO>()
                                    .in(MeetingPlanDO::getId, meetingPlanIds)
                    );
                    if (ObjectUtil.isNotEmpty(meetingPlanDOS)) {
                        // 拼接方案名称
                        String schemeNames = meetingPlanDOS.stream()
                                .map(MeetingPlanDO::getSchemeName)
                                .filter(Objects::nonNull)
                                .collect(Collectors.joining(","));
                        po.setSchemeName(schemeNames);
                        // 计算方案总价
                        BigDecimal totalSchemePrice = meetingPlanDOS.stream()
                                .map(MeetingPlanDO::getSchemePrice)
                                .filter(Objects::nonNull)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        po.setSchemePrice(totalSchemePrice);
                    }
                } catch (NumberFormatException e) {
                    // 处理转换异常，设置默认值
                    po.setSchemeName("数据解析错误");
                    po.setSchemePrice(BigDecimal.ZERO);
                }
            } else {
                // 如果没有会议方案ID，设置默认值
                po.setSchemeName("/");
                po.setSchemePrice(BigDecimal.ZERO);
            }
        }
        // 导出 Excel
        ExcelUtils.write(response, "会议报名信息.xls", "数据", ConferenceUserRegistrationInformationPO.class,
                list);
    }
}